import React from 'react'
import axios from 'axios'

export default function Search() {
    // 设置结果数组
    const [resultList,setResultList] = React.useState([]);
    // 标识input
    const myRef = React.useRef()

    const [selectIndex,setSelectIndex] = React.useState(0);

    let index = -1

    const handleKeyup = (e) => {
        if(e.keyCode === 40){
            index++;
            console.log(index);
            console.log(resultList[0]); //undefine
        }
    }
   
    React.useEffect( () => {
        document.addEventListener('keyup',handleKeyup)
    },[])

    function handleSearch() {
        // console.log(myRef.current.value);
        setResultList([]); //每次输入时清空上一次联想结果
        let kw = myRef.current.value;  //获取输入值
        if(!kw){
            return
        }
        // https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&wd=q&req=2&csor=1&cb=jQuery1102046009890276479415_1616297010245&_=1616297010246
        axios.get(`http://localhost:3000/api1/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&wd=${kw}`).then(
            (res) => {
                // console.log(res);
                setResultList(res.data.g);
            }
        )
    }
    return (
        <div>
            <input type="text" ref={myRef} onChange={handleSearch} placeholder="请输入关键字" id=""/>
            <ul>
                {
                    resultList?(resultList.length ? resultList.map((item) => {
                        return <li key={item.sa}>{item.q}</li>
                    }) : ''):''
                }
            </ul>
        </div>
    )
}
